//
//  UIView+CornerRadius.m
//  RentTable
//
//  Created by mac on 2024/11/30.
//

#import "UIView+CornerRadius.h"

@implementation UIView (CornerRadius)

- (void)setCornerRadius:(CGFloat)radius
           forCorners:(UIRectCorner)corners
           borderColor:(UIColor *)borderColor
           borderWidth:(CGFloat)borderWidth {
    
    [self layoutIfNeeded];
    
    // 创建路径，允许自定义哪些角需要圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                                   byRoundingCorners:corners
                                                         cornerRadii:CGSizeMake(radius, radius)];
    
    // 创建一个遮罩层，应用圆角
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    
    // 清除之前的边框层
    for (CAShapeLayer *sublayer in self.layer.sublayers) {
        if ([sublayer isKindOfClass:[CAShapeLayer class]] && sublayer != maskLayer) {
            [sublayer removeFromSuperlayer];
        }
    }
    
    // 创建边框层
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.frame = self.bounds;
    borderLayer.path = maskPath.CGPath;
    borderLayer.lineWidth = borderWidth;
    borderLayer.strokeColor = borderColor.CGColor;
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    
    // 将边框层添加到视图的layer
    [self.layer addSublayer:borderLayer];
}


@end
